package cn.wolfcode.web.controller;

import cn.wolfcode.qo.CustomerReportObjectQuery;
import cn.wolfcode.service.ICustomerReportService;
import cn.wolfcode.util.MessageUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/customerReport")
public class CustomerReportController {

    @Autowired
    private ICustomerReportService customerReportService;

    @RequestMapping("/list")
    public String list(Model model,@ModelAttribute("qo") CustomerReportObjectQuery qo) {
        model.addAttribute("pageInfo",customerReportService.query(qo));
        return "customerReport/list";
    }

    /**
     * 访问柱状图页面的方法
     * @param model
     * @param qo
     * @return
     */
    @RequestMapping("/bar")
    public String bar(Model model,@ModelAttribute("qo") CustomerReportObjectQuery qo) {
        //查询统计的数据
        List<HashMap> data = customerReportService.selectAll(qo);
        //准备两个集合
        ArrayList<Object> xList = new ArrayList<>();
        ArrayList<Object> yList = new ArrayList<>();
        //遍历两个集合
        for (HashMap map : data) {
            xList.add(map.get("groupType"));
            yList.add(map.get("number"));
        }
        //freemarker不能直接用${}获取集合，先转为字符串的形式，再共享到页面
        model.addAttribute("xList", JSON.toJSONString(xList));
        model.addAttribute("yList", JSON.toJSONString(yList));
        model.addAttribute("groupTypeName", MessageUtil.changMsg(qo));

        return "customerReport/bar";
    }

    /**
     * 访问饼图页面的方法
     * @param model
     * @param qo
     * @return
     */
    @RequestMapping("/pie")
    public String pie(Model model,@ModelAttribute("qo") CustomerReportObjectQuery qo) {
        //查询统计的数据
        List<HashMap> data = customerReportService.selectAll(qo);
        //准备两个集合
        ArrayList<Object> legend = new ArrayList<>();
        ArrayList<Object> series = new ArrayList<>();
        //遍历两个集合
        for (HashMap map : data) {
            legend.add(map.get("groupType"));

            HashMap<Object, Object> obj = new HashMap<>();
            obj.put("name", map.get("groupType"));
            obj.put("value", map.get("number"));
            series.add(obj);
        }
        //freemarker不能直接用${}获取集合，先转为字符串的形式，再共享到页面
        model.addAttribute("legend", JSON.toJSONString(legend));
        model.addAttribute("series", JSON.toJSONString(series));
        model.addAttribute("groupTypeName", MessageUtil.changMsg(qo));

        return "customerReport/pie";
    }
}
